<?php

set_error_handler('yErrorHandler');

/**
* error handler.
* This method is invoked by PHP when an error happens.
* It displays the error if the application state is in debug;
* otherwise, it saves the error in log.
*/
function yErrorHandler($errno, $errstr, $errfile, $errline) {/*{{{*/
	$errRpt=error_reporting();
	if(($errno & $errRpt)!=$errno)
		return;
	$msg="[$errno] $errstr (@line $errline in file $errfile).";
	yFatalError($msg);
}/*}}}*/

/**
* Fatal error handler.
* This method is used in places where exceptions usually cannot be raised
* (e.g. magic methods).
* It displays the debug backtrace if the application state is in debug;
* otherwise, only error message is displayed.
* @param string error message
*/
function yFatalError($msg) {/*{{{*/
	echo '<h1>Fatal Error</h1>';
	echo '<p>'.$msg.'</p>';
	if(!function_exists('debug_backtrace')) 
		return; 

	echo '<h2>Debug Backtrace</h2>';
	echo '<pre>';
	$index=-1;
	foreach(debug_backtrace() as $t) {
		$index++;
		if($index==0)  // hide the backtrace of this function
			continue;
		echo '#'.$index.' ';
		echo( isset($t['file']) ? 
			basename($t['file']) . ':' . $t['line'] : '<PHP inner-code>' );
		echo ' -- '; 

		if(isset($t['class']))
			echo $t['class'] . $t['type']; 
		echo $t['function']; 
		echo( (isset($t['args']) && sizeof($t['args']) > 0) ? '(...)' : '()' );
		echo "\n";
	}
	echo '</pre>';
	exit(1);
}/*}}}*/

?>
